#region (c) 2009 Abdullin.com and Contributors

// Copyright (c) 2009 Abdullin.com and Contributors
// Site: http://abdullin.com/ncouch
// This code is released under the terms of the new BSD licence

#endregion

using System;
using System.IO;
using Lokad;

namespace NCouch.Rest
{
	public sealed class RestClientDebuggingDecorator : IRestClient
	{
		public event Action<IRestRequest> OnRequest = request => { };
		public event Action<IRestResponse> OnResponse = response => { };

		readonly IRestClient _restClient;

		public RestClientDebuggingDecorator(IRestClient restClient)
		{
			_restClient = restClient;
		}

		IRestResponse IRestClient.GetResponse(IRestRequest request)
		{
			OnRequest(request);
			using(var response = _restClient.GetResponse(request))
			{
				var cached = new CachedRestResponse(response);
				OnResponse(cached);
				return cached;
			}
		}

		sealed class CachedRestResponse : IRestResponse
		{
			readonly Maybe<RestClientInjectionStream> _content = Maybe<RestClientInjectionStream>.Empty;
			public int StatusCode { get; private set; }
			public string ContentType { get; private set; }
			public long ContentLength { get; private set; }

			public CachedRestResponse(IRestResponse response)
			{
				StatusCode = response.StatusCode;
				ContentType = response.ContentType;
				ContentLength = response.ContentLength;

				var stream = new RestClientInjectionStream();
				response.RunReader(responseStream => responseStream.PumpTo(stream, 2.Kb()));
				_content = stream;

				//if (response.ContentLength > 0)
				//{
					
				//}
			}

			void IDisposable.Dispose()
			{
				_content.Apply(s =>
				{
					s.CanBeClosed = true;
					s.Dispose();
				});
			}

			void IRestResponse.RunReader(Action<Stream> read)
			{
				_content.Value.Seek(0, SeekOrigin.Begin);
				read(_content.Value);
			}
		}
	}
}